package linc.fun.openai.config.satoken;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import linc.fun.openai.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author linc
 * @date 2023-3-28
 * SaToken 配置，目前针对管理端鉴权
 */
@Slf4j
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
                    SaRouter.match("/admin/**", "/api/**").check(r -> {
                        tryCheckLogin();
                    });
                }))
                // 放行管理端登录接口
                .excludePathPatterns("/admin/sys_user/login")
                // 放行用户端校验邮箱验证码
                .excludePathPatterns("/api/chat_user/verify_email_code")
                // 放行用户端邮箱注册
                .excludePathPatterns("/api/chat_user/register_by_email")
                // 放行用户端邮箱登录
                .excludePathPatterns("/api/chat_user/login_by_email")
                // 获取图片验证码
                .excludePathPatterns("/api/captcha/get_pic_code")
//                .excludePathPatterns("/chat_pay/alipay/face2face/pay")
                // swagger 放行
//                .excludePathPatterns("/api/test/**")
                .excludePathPatterns("/swagger-ui/**")
                .excludePathPatterns("/v3/api-docs/**");
    }

    private void tryCheckLogin() {
        try {
            StpUtil.checkLogin();
        } catch (Exception e) {
            log.info("未登录用户: {}", e.getMessage());
            throw BizException.UN_AUTHENTICATION;
        }
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForStateless();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }

}
